//
//  RHDeviceBindVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/9/4.
//

#import "RHDeviceBindVC.h"
#import "RHUserModel.h"
#import "RHDeviceDistributeCell.h"
#import "RHNetworkTagVC.h"
#import "RHTagModel.h"
#import "RHSearchView.h"

@interface RHDeviceBindVC ()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate>
@property (nonatomic ,strong) UITableView *tableView;
//未绑定的(过滤跟电站类型一致)的设备
@property (nonatomic ,strong) NSMutableArray *notBindDevArr;

//总的设备
@property (nonatomic ,strong) NSMutableArray *totalDevArr;

@property(nonatomic,strong)NSMutableArray *DeviceSelectArr;

@property(nonatomic,strong)QMUIButton *distributeBtn;

@property (nonatomic, strong) RHSearchView *searchView;
@end

@implementation RHDeviceBindVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"绑定设备".rh_localized;
    [self getDevicesOfPlant];
    [self setupUI];
}

- (void)setupUI{
    _searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 55)];
    [self.view addSubview:_searchView];
    _searchView.delegate = self;
    _searchView.searchTextField.placeholder = @"请输入设备ID".rh_localized;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHDeviceDistributeCell class] forCellReuseIdentifier:@"RHDeviceDistributeCell"];
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        //_resultTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
        //_resultTableView.sectionHeaderTopPadding = 0;
    }
    
    _distributeBtn = [[QMUIButton alloc]init];
    [_distributeBtn setTitle:@"绑定".rh_localized forState:UIControlStateNormal];
    [_distributeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_distributeBtn setBackgroundColor:CMainColorGreen];
    _distributeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:19];
    _distributeBtn.layer.cornerRadius = 8;
    _distributeBtn.layer.masksToBounds = YES;
    [self.view addSubview:_distributeBtn];
    [_distributeBtn addTarget:self action:@selector(bindDeviceToPlant) forControlEvents:UIControlEventTouchUpInside];
    [_distributeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.bottom.mas_offset(-kSafe_bottom-20);
        make.height.offset(kScaleW(45));
    }];
    
    kWeakSelf;
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.searchView.mas_bottom);
        make.left.right.mas_offset(0);
        make.bottom.equalTo(weakSelf.distributeBtn.mas_top).offset(-20);
    }];
    
    
    [_tableView addHeaderRefresh:^{
        [weakSelf getDevicesOfPlant];
    }];
    
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
}





#pragma mark ----- 获取未绑定到电站下的设备列表
-(void)getDevicesOfPlant
{
    //未绑定
    [QMUITips showLoadingInView:self.view];
    [RHDeviceModel startGetWithCompletionAPIKey:H_getNoAddPlantDeviceList argument:@{@"page":@(1),@"deviceId":ValidNullData(self.searchView.searchTextField.text),@"plantId":@(self.plantModel.plant_id)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.totalDevArr removeAllObjects];
        [self.DeviceSelectArr removeAllObjects];
        self.notBindDevArr = [resultModel.data mutableCopy];
        
        NSMutableArray *mtbArr = [NSMutableArray array];
        [self.notBindDevArr enumerateObjectsUsingBlock:^(RHDeviceModel  *_Nonnull deviceModel, NSUInteger idx, BOOL * _Nonnull stop) {
            //过滤跟电站类型一致的设备
            if([deviceModel.deviceTypeCode isEqualToString:self.plantModel.plantType]){
                [mtbArr addObject:deviceModel];
            }
           
        }];
        self.notBindDevArr = mtbArr;
        
        [self.totalDevArr addObjectsFromArray:self.notBindDevArr];
        [self.tableView reloadData];
        [self.tableView endHeaderRefresh];
        [self.distributeBtn setTitle:[NSString stringWithFormat:@"%@(%ld/%ld)",@"绑定".rh_localized,self.DeviceSelectArr.count,self.totalDevArr.count] forState:UIControlStateNormal];
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
        
    }];
    
}


#pragma mark ----- 绑定/解绑 设备到电站下(终端用户)

-(void)bindDeviceToPlant
{
    NSMutableArray *addDeviceIDs = [NSMutableArray array];
   
    for (RHDeviceModel *device in self.DeviceSelectArr) {
        //只对没有添加的设备进行添加
        if(!device.isBind){
            [addDeviceIDs addObject:@{@"deviceId":device.deviceId,@"netTag":@(device.netTag)}];
        }
    }
  
    NSDictionary *add_para = @{@"plantId":@(self.plantModel.plant_id),
                           @"plantDeviceDtoList":addDeviceIDs
    };

    //已选择的设备,包括要添加和要删除的
    if(addDeviceIDs.count>0){
        [QMUITips showLoading:@"绑定...".rh_localized inView:self.view];
        [BaseModel startWithCompletionAPIKey:H_addPlantDevices argument:add_para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
               
                [QMUITips showSucceed:@"成功".rh_localized];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter]postNotificationName:DeviceListNeedUpdateNotification object:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                });
            
            }
            
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
           
            
        }];
    }
    
}



#pragma mark ------ tableView delegate --------

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.totalDevArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHDeviceDistributeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHDeviceDistributeCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.deviceModel = self.totalDevArr[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RHDeviceModel *model = self.totalDevArr[indexPath.row];
   
    kWeakSelf;
    //如果设备是离线状态,要选择离线原因
    if([model.status isEqualToString:@"1"]&& !model.isSelected){
        [QMUITips showLoadingInView:self.view];
        [RHTagModel startGetWithCompletionAPIKey:H_getNetTags argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
               
                NSArray *tagArr = resultModel.data;
              
                RHNetworkTagVC *vc = [[RHNetworkTagVC alloc] initWithTitle:@"请选择离线原因".rh_localized Data:tagArr];
                [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
            
                vc.selectBlock = ^(NSInteger index) {
                    RHTagModel *tagModel = tagArr[index];
                    model.netTag = tagModel.netTag;
                    
                    model.isSelected = !model.isSelected;
                    if(model.isSelected){
                        [weakSelf.DeviceSelectArr addObject:model];
                    }else{
                        [weakSelf.DeviceSelectArr removeObject:model];
                    }
                    [weakSelf.tableView reloadData];
                    [self.distributeBtn setTitle:[NSString stringWithFormat:@"%@(%zd/%zd)",@"绑定".rh_localized,self.DeviceSelectArr.count,self.totalDevArr.count] forState:UIControlStateNormal];
                };
            }
            
            
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
        
    }else{
        
        model.isSelected = !model.isSelected;
        if(model.isSelected){
            [self.DeviceSelectArr addObject:model];
        }else{
            [self.DeviceSelectArr removeObject:model];
        }
        [self.tableView reloadData];
        
    }
    
  
    [self.distributeBtn setTitle:[NSString stringWithFormat:@"%@(%zd/%zd)",@"绑定".rh_localized,self.DeviceSelectArr.count,self.totalDevArr.count] forState:UIControlStateNormal];
    
}

#pragma mark ------- textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
    [self getDevicesOfPlant];
    [self.searchView resignFirstResponder];
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getDevicesOfPlant];
        [self.searchView resignFirstResponder];
    });
    return YES;
}


-(NSMutableArray *)DeviceSelectArr
{
    if(!_DeviceSelectArr){
        _DeviceSelectArr = [NSMutableArray array];
    }
    return _DeviceSelectArr;
}
-(NSMutableArray *)notBindDevArr
{
    if(!_notBindDevArr){
        _notBindDevArr = [NSMutableArray array];
    }
    return _notBindDevArr;
}

-(NSMutableArray *)totalDevArr
{
    if(!_totalDevArr){
        _totalDevArr = [NSMutableArray array];
    }
    return _totalDevArr;
}
@end
